import shiki from '@shikijs/markdown-it'
import markdownAnchor from 'markdown-it-anchor'
import markdownVue from 'unplugin-vue-markdown/vite'
import markdownToc from 'markdown-it-toc-done-right'
import markdownCustomContainer from 'markdown-it-container'

export async function markdown(): Promise<ReturnType<typeof markdownVue>> {
  return markdownVue({
    async markdownItSetup(md) {
      md.use(markdownAnchor)
      md.use(markdownToc, {
        level: [2, 3],
        containerId: 'markdown-toc'
      })
      md.use(
        await shiki({
          theme: 'material-theme-palenight',
          langs: ['matlab', 'markdown', 'python']
        })
      )
      defineCustomContainer(md)
    }
  })
}

function defineCustomContainer(md: MarkdownIt): void {
  ;['note', 'warning', 'danger', 'success'].forEach((name) =>
    markdownCustomContainer(md, ...createCustomContainer(name))
  )
}

function createCustomContainer(name: string): [string, any] {
  return [
    name,
    {
      validate: (params: string) => !!params.trim().match(new RegExp(`^${name}\\s*(.*)$`))
    }
  ]
}
